package cn.doitedu.javase.socket.demo2;


import java.io.*;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws IOException {

        // 建立连接
        Socket socket = new Socket("localhost", 9088);

        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();

        InputStreamReader ir = new InputStreamReader(is, "UTF-8");
        OutputStreamWriter ow = new OutputStreamWriter(os, "UTF-8");


        // 发送天王盖地虎
        ow.write("111天王盖地虎222");
        ow.flush();

        char[] chars = new char[11];
        int read = ir.read(chars);
        if (read == 11 && new String(chars).equals("333宝塔镇河妖444")) {
            System.out.println("认证成功");
        } else {
            System.out.println("认证失败");
            System.out.println(new String(chars));
            ow.close();
            ir.close();
            socket.close();
            System.exit(1);
        }


        // 认证通过后，开始发送真实信息
        ow.write("111客户端发送的真实内容222");
        ow.flush();

        // 接收服务端的响应
        char[] singleChar = new char[1];
        char[] contentChar = new char[1024];
        int idx = 0;
        int head = 0;
        int tail = 0;
        while ((read = ir.read(singleChar)) != -1) {
            // 接收响应头
            if (singleChar[0] == '3' && head < 3) {
                head++;
            }

            // 接收内容
            if (singleChar[0] != '4') {
                contentChar[idx] = singleChar[0];
                idx++;
            } else {
                tail++;
                if (tail == 3) {
                    // 处理服务端的响应内容
                    System.out.println(new String(contentChar, 0, idx));
                    break;
                }
            }
        }

        ow.close();
        ir.close();
        socket.close();

    }

}
